<template>
  <!-- 商品管理 -->
  <div class="p-2">
    <!-- 顶部搜索 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="showSearch">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model.trim="queryParams.name" placeholder="请输入" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item label="商品编号" prop="sn">
              <el-input v-model.trim="queryParams.sn" placeholder="请输入" clearable style="width: 200px" />
            </el-form-item>
<!--            <el-form-item label="商品类型" prop="type">-->
<!--              <el-select v-model="queryParams.type" placeholder="请选择" clearable style="width: 90px">-->
<!--                <el-option label="月会员" value="MONTH" />-->
<!--                <el-option label="年会员" value="YEAR" />-->
<!--                <el-option label="永久会员" value="PERMANENT" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <el-form-item label="状态" prop="enable">
              <el-select v-model="queryParams.enable" placeholder="请选择" clearable style="width: 200px">
                <el-option label="上架" :value="1" />
                <el-option label="下架" :value="0" />
              </el-select>
            </el-form-item>
<!--            <el-form-item label="组合" prop="compose">-->
<!--              <el-select v-model="queryParams.compose" placeholder="请选择" clearable style="width: 90px">-->
<!--                <el-option label="是" :value="1" />-->
<!--                <el-option label="否" :value="0" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <el-form-item>
              <el-button type="primary" @click="handleQuery" icon="Search" v-hasPermi="['gms:goods:query']">搜索</el-button>
              <el-button @click="resetQuery" icon="Refresh">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="hover">
      <!-- 功能按钮 -->
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain @click="handleAdd()" icon="Plus" v-hasPermi="['gms:goods:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain :disabled="single" icon="Edit" @click="handleUpdate()"
              v-hasPermi="['gms:goods:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain :disabled="single" icon="Delete" @click="handleDelete()"
              v-hasPermi="['gms:goods:remove']">删除</el-button>
          </el-col> -->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="warning" plain icon="Download" @click="handleDownload()"-->
<!--              v-hasPermi="['gms:goods:export']">导出</el-button>-->
<!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"
            :search="true"></right-toolbar>
        </el-row>
      </template>
      <!-- 表格 -->
      <el-table ref="supTableRef" v-loading="loading" :data="goodsList" max-height="550" border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="商品编号" prop="sn" align="center" width="120" v-if="columns[0].visible" />-->
        <el-table-column label="商品名称" prop="name" align="center" :show-overflow-tooltip="true" width="160"
          v-if="columns[1].visible" />
        <el-table-column label="商品类型" prop="type" align="center" width="120" v-if="columns[2].visible">
          <template #default="scope">{{ typeFilters(scope.row.type) }}</template>
        </el-table-column>
<!--        <el-table-column label="封面" prop="cover" align="center" min-width="120" v-if="columns[3].visible">-->
<!--          <template #default="scope">-->
<!--            <el-image style="width: 80px; height: 80px"-->
<!--              :src="scope.row.cover "-->
<!--              :preview-src-list="[scope.row.cover]" fit="contain" :preview-teleported="true" />-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="小图" prop="smallPic" align="center" min-width="120" v-if="columns[4].visible">-->
<!--          <template #default="scope">-->
<!--            <el-image style="width: 80px; height: 80px"-->
<!--              :src="scope.row.smallPic "-->
<!--              :preview-src-list="[scope.row.smallPic]" fit="contain" :preview-teleported="true" />-->
<!--          </template>-->
<!--        </el-table-column>-->

<!--        <el-table-column label="划线价" prop="marketPrice" align="center" width="" v-if="columns[6].visible" />-->
        <el-table-column label="售价" prop="price" align="center" width="" v-if="columns[7].visible" />
<!--        <el-table-column label="成本价" prop="cost" align="center" width="" v-if="columns[8].visible" />-->
<!--        <el-table-column label="寄卖差价" prop="saleRebate" align="center" width="" v-if="columns[9].visible" />-->
<!--        <el-table-column label="买手直推反佣" prop="directBuyerRebate" align="center" width="110" v-if="columns[10].visible" />-->
<!--        <el-table-column label="买手间推反佣" prop="indirectBuyerRebate" align="center" width="110"-->
<!--          v-if="columns[11].visible" />-->
<!--        <el-table-column label="卖手直推反佣" prop="directSellerRebate" align="center" width="110" v-if="columns[12].visible" />-->
<!--        <el-table-column label="卖手间推反佣" prop="indirectSellerRebate" align="center" width="110"-->
<!--          v-if="columns[13].visible" />-->
<!--        <el-table-column label="库存" prop="stock" align="center" width="" v-if="columns[14].visible" />-->
        <el-table-column label="AppId" prop="supplierId" align="center" :show-overflow-tooltip="true" width="180"
          v-if="columns[15].visible" />
        <el-table-column label="App名称" prop="supplierName" align="center" width="100" v-if="columns[16].visible" />
<!--        <el-table-column label="京东仓库" prop="warehouseCode" align="center" width="100" v-if="columns[17].visible">-->
<!--          <template #default="scope">-->
<!--            <dict-tag :options="warehose_code" :value="scope.row.warehouseCode" />-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="组合商品" prop="compose" align="center" width="100" v-if="columns[18].visible">-->
<!--          <template #default="scope">{{ composeFilters(scope.row.compose) }}</template>-->
<!--        </el-table-column>-->
        <el-table-column label="排序" prop="sortNum" align="center" width="" v-if="columns[19].visible" />
        <el-table-column fixed="right" label="上架状态" prop="enable" align="center" width="" v-if="columns[5].visible">
          <!-- <template #default="scope">{{ enableFilters(scope.row.enable) }}</template> -->
          <template #default="scope">
            <el-switch v-model="scope.row.enable" :active-value="1" :inactive-value="0" @change="approve(scope.row)"
              :disabled="enableFlag"></el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="创建时间" prop="createTime" align="center" width="140"
          v-if="columns[19].visible">
          <template #default="scope">{{ scope.row.createTime.slice(0, -3) }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="120">
          <template #default="scope">
<!--            <el-tooltip content="详情" placement="top">-->
<!--              <el-button link type="primary" icon="View" @click="handleDetails(scope.row)"></el-button>-->
<!--            </el-tooltip>-->
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['gms:goods:edit']"></el-button>
            </el-tooltip>
            <!-- <el-tooltip content="审核" placement="top">
              <el-button link type="primary" icon="Open" @click="approve(scope.row)"
                v-hasPermi="['gms:goods:updown']"></el-button>
            </el-tooltip> -->
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['gms:goods:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup lang="ts" name="Goods">
import { listGoods, delGoods, enableGoods } from '@/api/operates/goods/index';
import { GoodsQuery, GoodsVO, GoodsForm } from '@/api/operates/goods/types';
import useUserStore from '@/store/modules/user';
const permissions = useUserStore().permissions;
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { warehose_code } = toRefs<any>(proxy?.useDict('warehose_code'));

const goodsList = ref<GoodsVO[]>([]);
const loading = ref(true)
const showSearch = ref(true)
const ids = ref<Array<string | number>>([])
const infos = ref<GoodsVO[]>([])
const single = ref(true)
const multiple = ref(true)
const enableFlag = ref(false)
const total = ref(0)

const columns = ref<FieldOption[]>([
  { key: 0, label: `商品编号`, visible: true, children: [] },
  { key: 1, label: `商品名称`, visible: true, children: [] },
  { key: 2, label: `显示位置`, visible: true, children: [] },
  { key: 3, label: `封面`, visible: true, children: [] },
  { key: 4, label: `小图`, visible: true, children: [] },
  { key: 5, label: `上架状态`, visible: true, children: [] },
  { key: 6, label: `划线价`, visible: true, children: [] },
  { key: 7, label: `售价`, visible: true, children: [] },
  { key: 8, label: `成本价`, visible: true, children: [] },
  { key: 9, label: `寄卖差价`, visible: true, children: [] },
  { key: 10, label: `买手直推反佣`, visible: true, children: [] },
  { key: 11, label: `买手间推反佣`, visible: true, children: [] },
  { key: 12, label: `卖手直推反佣`, visible: true, children: [] },
  { key: 13, label: `卖手间推反佣`, visible: true, children: [] },
  { key: 14, label: `库存`, visible: true, children: [] },
  { key: 15, label: `供应商id`, visible: true, children: [] },
  { key: 16, label: `供应商名称`, visible: true, children: [] },
  { key: 17, label: `京东仓库`, visible: true, children: [] },
  { key: 18, label: `组合商品`, visible: true, children: [] },
  { key: 19, label: `排序`, visible: true, children: [] },
  { key: 20, label: `创建时间`, visible: true, children: [] },
])

const queryFormRef = ref<ElFormInstance>();

const data = reactive<PageData<null, GoodsQuery>>({
  form: null,
  queryParams: {
    name: '',
    sn: '',
    type: '',
    pageNum: 1,
    pageSize: 10,
  },
  rules: {}
})
const { queryParams } = toRefs(data)

/**
 * 查询商品列表
 */
const getList = async () => {
  loading.value = true
  const res = await listGoods(queryParams.value);
  goodsList.value = res.data.list;
  total.value = res.data.total;
  loading.value = false;
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/**
 * 重置搜索
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/**
 * 过滤（显示位置）
 * @param val
 */
const typeFilters = (val: string) => {
  if (val === 'YEAR') {
    return '年会员'
  } else if (val === 'MONTH') {
    return '月会员'
  } else {
    return '永久会员'
  }
}

/**
 * 过滤（上架下架）
 * @param val
 */
const enableFilters = (val: number) => {
  if (val === 1) {
    return '上架'
  } else if (val === 0) {
    return '下架'
  }
}

/**
 * 过滤（是否是组合商品）
 * @param val
 */
const composeFilters = (val: number) => {
  if (val === 1) {
    return '组合商品'
  } else if (val === 0) {
    return '非组合商品'
  }
}

/**
 * 导出
 */
const handleDownload = () => {
  const queryExport = { ...queryParams.value }
  delete queryExport.pageNum
  delete queryExport.pageSize
  proxy?.download('/goods/export', {
    ...queryExport
  }, `商品记录.xlsx`)
}

/**
 * 多选框选中数据
 * @param selection
 */
const handleSelectionChange = (selection: GoodsVO[]) => {
  ids.value = selection.map((item: GoodsVO) => item.id);
  infos.value = selection.map((item: GoodsVO) => item);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/**
 * 商品添加
 */
const handleAdd = () => {
  router.push({ path: "/goods/add" });
}

/**
 * 商品详情
 * @param row
 */
const handleDetails = (row: GoodsVO) => {
  const id = row.id
  // router.push({ path: `/goods/details/${id}` });
  router.push({ path: `/goods/details`, query: { id } });
}

/**
 * 商品修改
 * @param row
 */
const handleUpdate = (row?: GoodsVO) => {
  const id = row?.id || ids.value[0]
  router.push({ path: `/goods/edit/${id}` });
}

/**
 * 审核{上架/下架}
 * @param row
 */
const approve = async (row: GoodsVO) => {
  try {
    let text = row.enable === 1 ? "启用" : "禁用";
    await enableGoods(row.id);
    getList();
    proxy?.$modal.msgSuccess(text + "成功");
  } catch (error) {
    row.enable = row.enable === 1 ? 0 : 1;
  }
}

/**
 * 商品删除
 * @param row
 */
const handleDelete = async (row?: GoodsVO) => {
  try {
    const goods = row || infos.value[0];
    if (goods.enable == 1) {
      proxy?.$modal.msgError('请先执行禁用操作');
      return
    }
    await proxy?.$modal.confirm('是否确认删除商品');
    await delGoods(goods.id);
    getList();
    proxy?.$modal.msgSuccess('删除成功');
  } catch (error) { }
}

const enableFn = () => {
  // '*:*:*'
  // enableFlag
  if (permissions[0] !== '*:*:*') {
    enableFlag.value = !permissions.includes('gms:goods:updown')
  }
}

onMounted(() => {
  getList();
  enableFn();
});

onUpdated(() => {
  getList();
  enableFn();
})

</script>
<style scoped></style>
